package com.chookss.home.knowledge.adaper;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.WebCommonActivity;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.Token;
import com.chookss.home.document.DocumentDetailActivity;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.document.DownloadService;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.home.entity.FileEntity;
import com.chookss.home.entity.GalleryListEntity;
import com.chookss.home.studyPlan.StudyPlanAddActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.bigImage.ImagePreview;
import com.chookss.tools.bigImage.bean.ImageInfo;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.VideoOnePlayActivity;
import com.chookss.video.entity.VideoEntity;
import com.chookss.video.recommend.VedioDetailActivity;
import com.chookss.view.BottomListsDialog;
import com.chookss.view.ForScreenInitDialog;
import com.chookss.view.SelectDialogListener;
import com.chookss.view.listener.ShareDialogListener;
import com.chookss.wxapi.ShareActivity;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.annotations.Nullable;

public class JustOpenListAdapter extends BaseQuickAdapter<FileEntity.ListBean, BaseViewHolderEx> {
    private Activity context;
    private String tag;//记录来源
    private boolean isTask = false;
    private BottomListsDialog bottomListsDialog = null;
    private List<String> dialogDocunmentList = new ArrayList<>();
    private List<String> dialogVideoList = new ArrayList<>();
    private List<String> dialogSmallVideoList = new ArrayList<>();
    private List<String> dialogPicList = new ArrayList<>();
    private List<String> dialogTuwenList = new ArrayList<>();

    public JustOpenListAdapter(int layoutResId, Activity context, @Nullable List<FileEntity.ListBean> data, String tag) {
        super(layoutResId, data);
        this.context = context;
        this.tag = tag;
        dialogDocunmentList.add("分享");
        dialogDocunmentList.add("在电脑上查看");
        dialogDocunmentList.add("加入学习任务");
        dialogDocunmentList.add("查看");
        dialogDocunmentList.add("详细信息");
        dialogDocunmentList.add("取消");
        dialogVideoList.add("分享");
        dialogVideoList.add("在电脑上播放");
        dialogVideoList.add("视频加入学习任务");
        dialogVideoList.add("取消");
        dialogSmallVideoList.add("分享");
        dialogSmallVideoList.add("在电脑上播放");
        dialogSmallVideoList.add("视频加入学习任务");
        dialogSmallVideoList.add("取消");
        dialogPicList.add("查看原图");
        dialogPicList.add("取消");
        dialogTuwenList.add("查看");
        dialogTuwenList.add("取消");
    }

    @Override
    protected void convert(BaseViewHolderEx helper, FileEntity.ListBean entity) {
        ImageView ivIconType = helper.getView(R.id.ivIconType);
        ImageView ivMore = helper.getView(R.id.ivMore);
        LinearLayout llMore = helper.getView(R.id.llMore);
        LinearLayout llInit = helper.getView(R.id.llInit);
        TextView tvItemTitle = helper.getView(R.id.tvItemTitle);
        TextView tvTime = helper.getView(R.id.tvTime);
        TextView tvSize = helper.getView(R.id.tvSize);
        ProgressBar progressBar = helper.getView(R.id.progressBar);
//        （1资料，2长视频，3短视频，4新闻，5图文6图片）
        int resourceType = Utils.changeNumber(entity.getResourceType());
        tvItemTitle.setText(entity.getResourceName());
        ivMore.setVisibility(View.VISIBLE);
        if (resourceType == 1) {
            if (entity.getProgress() == 0 || entity.getProgress() == 100) {
                progressBar.setVisibility(View.INVISIBLE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(entity.getProgress());
            }
            String fileType = entity.getRemarks();//文件类型1--word 2 --excel 3--PPT  4pdf
            if ("1".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_w_80).into(ivIconType);
            } else if ("2".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_x_80).into(ivIconType);
            } else if ("3".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_p_80).into(ivIconType);
            } else if ("4".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_pdf_80).into(ivIconType);
            } else {
                Glide.with(context).load(R.drawable.icon_mr_80).into(ivIconType);
            }
        } else if (resourceType == 2 || resourceType == 3) {
            progressBar.setVisibility(View.INVISIBLE);
            GlideUtils.loadCustomRound(context, entity.getRemarks(), ivIconType, 4);
        } else if (resourceType == 4 || resourceType == 5) {
            progressBar.setVisibility(View.INVISIBLE);
            if (Utils.isNull(entity.getRemarks())) {
                Glide.with(context).load(R.drawable.icon_news_80).into(ivIconType);
            } else {
                GlideUtils.loadCustomRound(context, entity.getRemarks(), ivIconType, 4);
            }
        } else if (resourceType == 6) {
            progressBar.setVisibility(View.INVISIBLE);
            if (Utils.isNull(entity.getRemarks())) {
                Glide.with(context).load(R.drawable.iv_default_tag).into(ivIconType);
            } else {
                GlideUtils.loadCustomRound(context, entity.getRemarks(), ivIconType, 4);
            }
        }
        tvTime.setText(Utils.getAccurateDate(entity.getCreateTime()));
        tvSize.setText(Utils.changeKM(entity.getResourceSize()));
        helper.getItemView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Urls.antiShake.check()) {
                    return;
                }
                if (resourceType == 1) {
                    requestSTORAGE(entity.getResourceId(), tvItemTitle.getText().toString(), helper.getItemPosition(),entity.isError());
                } else if (resourceType == 2 || resourceType == 3) {
                    getVideo(entity.getResourceId(), resourceType);
                } else if (resourceType == 5) {
                    toTuwenDetails(entity);
                } else if (resourceType == 6) {
                    getPicDetail(entity.getResourceId());
                }
            }
        });
        llMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Urls.antiShake.check()) {
                    return;
                }
                if (resourceType == 1) {
                    bottomListsDialog = new BottomListsDialog(context, dialogDocunmentList, new SelectDialogListener() {
                        @Override
                        public void onCancel() {
                        }

                        @Override
                        public void onListItemClick(int position, List<String> list) {
                            if (position == 0) {
                                Intent intent = new Intent(context, ShareActivity.class);
                                intent.putExtra("title", entity.getResourceName());
                                intent.putExtra("createEmployeeName", entity.getCreateUser());
                                intent.putExtra("content", entity.getKeyWord());
                                intent.putExtra("resourceId", entity.getResourceId());
                                intent.putExtra("size", tvSize.getText().toString());
                                intent.putExtra("resourceType", 1);
                                context.startActivity(intent);
                            } else if (position == 1) {
                                new ForScreenInitDialog(context, new ShareDialogListener() {
                                    @Override
                                    public void onClick() {
                                        saveScan(entity.getResourceId(), "1");
                                    }
                                }).show();
                            } else if (position == 2) {
                                Intent intent = new Intent(context, StudyPlanAddActivity.class);
                                intent.putExtra("resourceId", entity.getResourceId());
                                intent.putExtra("describe", entity.getKeyWord());
                                intent.putExtra("resourceType", 5);
                                intent.putExtra("title", entity.getResourceName());
                                intent.putExtra("content", entity.getKeyWord());
                                intent.putExtra("size", tvSize.getText().toString());
                                context.startActivity(intent);
                            } else if (position == 3) {
                                requestSTORAGE(entity.getResourceId(), tvItemTitle.getText().toString(), helper.getItemPosition(),entity.isError());
                            } else if (position == 4) {
                                //详细信息
                                Intent intent = new Intent(context, DocumentDetailActivity.class);
                                intent.putExtra("dataCode", entity.getResourceId());
                                context.startActivity(intent);
                            }
                            bottomListsDialog.dismiss();
                        }
                    });
                    bottomListsDialog.show();
                } else if (resourceType == 2) {
                    //长视频
                    List<String> newList = new ArrayList<>();
                    newList.addAll(dialogVideoList);
                    if (!Utils.isNull(entity.getCourseCode())) {
                        newList.add(3, "课程加入学习任务");
                    }
                    bottomListsDialog = new BottomListsDialog(context, newList, new SelectDialogListener() {
                        @Override
                        public void onCancel() {
                        }

                        @Override
                        public void onListItemClick(int position, List<String> list) {
                            if (position == 0) {
                                Intent intent = new Intent(context, ShareActivity.class);
                                intent.putExtra("title", entity.getResourceName());
                                intent.putExtra("createEmployeeName", entity.getCreateUser());
                                intent.putExtra("content", entity.getKeyWord());
                                intent.putExtra("resourceId", entity.getResourceId());
                                intent.putExtra("videoShareCounts", entity.getShareNum());
                                intent.putExtra("time", entity.getVideoSecounds());
                                intent.putExtra("picUrl", entity.getRemarks());
                                intent.putExtra("resourceType", 2);
                                context.startActivity(intent);
                            } else if (position == 1) {
                                new ForScreenInitDialog(context, new ShareDialogListener() {
                                    @Override
                                    public void onClick() {
                                        saveScan(entity.getResourceId(), "2");
                                    }
                                }).show();
                            } else if (position == 2) {
                                Intent intent = new Intent(context, StudyPlanAddActivity.class);
                                intent.putExtra("title", entity.getResourceName());
                                intent.putExtra("describe", entity.getKeyWord());
                                intent.putExtra("resourceId", entity.getResourceId());
                                intent.putExtra("resourceType", 2);
                                intent.putExtra("time", entity.getVideoSecounds());
                                intent.putExtra("picUrl", entity.getRemarks());
                                context.startActivity(intent);
                            } else if (position == 3) {
                                if (!Utils.isNull(entity.getCourseCode())) {
                                    Intent intent = new Intent(context, StudyPlanAddActivity.class);
                                    intent.putExtra("title", entity.getResourceName());
                                    intent.putExtra("describe", entity.getKeyWord());
                                    intent.putExtra("resourceId", entity.getResourceId());
                                    intent.putExtra("resourceType", 4);
                                    context.startActivity(intent);
                                }
                            }
                            bottomListsDialog.dismiss();
                        }
                    });
                    bottomListsDialog.show();
                } else if (resourceType == 3) {
                    //小视频
                    List<String> newList = new ArrayList<>();
                    newList.addAll(dialogVideoList);
                    if (!Utils.isNull(entity.getVideoCollectionsCode())) {
                        newList.add(3, "集合加入学习任务");
                    }
                    bottomListsDialog = new BottomListsDialog(context, newList, new SelectDialogListener() {
                        @Override
                        public void onCancel() {
                        }

                        @Override
                        public void onListItemClick(int position, List<String> list) {
                            if (position == 0) {
                                Intent intent = new Intent(context, ShareActivity.class);
                                intent.putExtra("title", entity.getResourceName());
                                intent.putExtra("createEmployeeName", entity.getCreateUser());
                                intent.putExtra("content", entity.getKeyWord());
                                intent.putExtra("resourceId", entity.getResourceId());
                                intent.putExtra("videoShareCounts", entity.getShareNum());
                                intent.putExtra("time", entity.getVideoSecounds());
                                intent.putExtra("picUrl", entity.getRemarks());
                                intent.putExtra("resourceType", 3);
                                context.startActivity(intent);
                            } else if (position == 1) {
                                new ForScreenInitDialog(context, new ShareDialogListener() {
                                    @Override
                                    public void onClick() {
                                        saveScan(entity.getResourceId(), "3");
                                    }
                                }).show();
                            } else if (position == 2) {
                                Intent intent = new Intent(context, StudyPlanAddActivity.class);
                                intent.putExtra("title", entity.getResourceName());
                                intent.putExtra("describe", entity.getKeyWord());
                                intent.putExtra("resourceId", entity.getResourceId());
                                intent.putExtra("resourceType", 1);
                                intent.putExtra("time", entity.getVideoSecounds());
                                intent.putExtra("picUrl", entity.getRemarks());
                                context.startActivity(intent);
                            } else if (position == 3) {
                                if (!Utils.isNull(entity.getCourseCode())) {
                                    Intent intent = new Intent(context, StudyPlanAddActivity.class);
                                    intent.putExtra("title", entity.getResourceName());
                                    intent.putExtra("describe", entity.getKeyWord());
                                    intent.putExtra("resourceId", entity.getResourceId());
                                    intent.putExtra("resourceType", 3);
                                    context.startActivity(intent);
                                }
                            }
                            bottomListsDialog.dismiss();
                        }
                    });
                    bottomListsDialog.show();
                }  else if (resourceType == 5) {
                    //图片
                    List<String> newList = new ArrayList<>();
                    newList.addAll(dialogTuwenList);
                    bottomListsDialog = new BottomListsDialog(context, newList, new SelectDialogListener() {
                        @Override
                        public void onCancel() {
                        }

                        @Override
                        public void onListItemClick(int position, List<String> list) {
                            if (position == 0) {
                                toTuwenDetails(entity);
                            }
                            bottomListsDialog.dismiss();
                        }
                    });
                    bottomListsDialog.show();
                }else if (resourceType == 6) {
                    //图片
                    List<String> newList = new ArrayList<>();
                    newList.addAll(dialogPicList);
                    bottomListsDialog = new BottomListsDialog(context, newList, new SelectDialogListener() {
                        @Override
                        public void onCancel() {
                        }

                        @Override
                        public void onListItemClick(int position, List<String> list) {
                            if (position == 0) {
                                getPicDetail(entity.getResourceId());
                            }
                            bottomListsDialog.dismiss();
                        }
                    });
                    bottomListsDialog.show();
                }
            }
        });
    }
    private void toTuwenDetails(FileEntity.ListBean entity){
        NavigationTools.saveUseRecord(context, "1", "17");
        String addressType = "";
        if (Urls.baseUrl.contains("dev_kmer")) {
            addressType = "1";
        } else {
            addressType = "0";
        }
        Intent intent = new Intent(context, WebCommonActivity.class);
        String url = Urls.tuwenDetail + "mainCode=" + entity.getResourceId() + "&token=" + Token.INSTANCE.getToken() + "&statusHeight=" + Utils.getStatusBarHeightDp(context) + "&time=" + System.currentTimeMillis() + "&addressType=" + addressType;
        intent.putExtra("url", url);
        intent.putExtra("title", "详情");
        intent.putExtra("isTuwen", 3);
        if (Utils.isNull(entity.getRemarks())) {
            intent.putExtra("picUrl", "");
        } else {
            intent.putExtra("picUrl", entity.getRemarks());
        }
        intent.putExtra("createEmployeeName", entity.getCreateUser());
        intent.putExtra("newsTitle", entity.getResourceName());
        intent.putExtra("newsContent", "");
        intent.putExtra("resourceId", entity.getResourceId());
        intent.putExtra("waterMark", "13");
        intent.putExtra("url", url);
        context.startActivity(intent);
    }

    private void requestSTORAGE(String code, String retitle, int rePosition,boolean isError) {
        XXPermissions.with(context)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            getDocunmentDetail(code, retitle, rePosition,isError);
                        } else {
                            MyToast.show("存储未被授权，请先去权限设置里面授权");
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(context, denied, quick);
                    }
                });
    }

    private void getDocunmentDetail(String code, String docTitle, int docPosition,boolean isError) {
        Map<String, String> map = new HashMap<>();
        map.put("dataCode", code);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DocunmentEntity>>() {
        }.getType(), null, Urls.getDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<DocunmentEntity>() {
            @Override
            public void onSuccess(DocunmentEntity newData) {
                if (newData != null) {
                    openFile(newData, docTitle, docPosition,isError);
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getPicDetail(String imageCode) {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("imageCode", imageCode);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<GalleryListEntity.ImagePathListBean>>() {
        }.getType(), null, Urls.getImageDetail, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<GalleryListEntity.ImagePathListBean>() {
            @Override
            public void onSuccess(GalleryListEntity.ImagePathListBean data) {
                if (data != null) {
                    List<ImageInfo> imageInfoList = new ArrayList<>();
                    imageInfoList.add(dealData(data));
                    ImagePreview.getInstance()
                            .setContext(context)
                            // 设置从第几张开始看（索引从0开始）
                            .setIndex(0)
                            .setShowCloseButton(true)
                            .setToNewView(true)
                            .setLoadStrategy(ImagePreview.LoadStrategy.NetworkAuto)
                            .setImageInfoList(imageInfoList)
                            .start();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private ImageInfo dealData(GalleryListEntity.ImagePathListBean imagePathListBean) {
        ImageInfo imageInfo = new ImageInfo();
        String originUrl = imagePathListBean.getImagePath().split("\\?")[0];
//                    imageInfo.setThumbnailUrl(originUrl+"?x-oss-process=image/resize,m_lfit,w_720");
        imageInfo.setThumbnailUrl(originUrl);
        imageInfo.setOriginUrl(originUrl);
        imageInfo.setImageCode(imagePathListBean.getImageCode());
        if (Utils.isNull(imagePathListBean.getProvideEmployeeName())) {
            imageInfo.setName(imagePathListBean.getCreateEmployeeName());
        } else {
            imageInfo.setName(imagePathListBean.getProvideEmployeeName());
        }
        String date = imagePathListBean.getCreateTime();
        if (!Utils.isNull(date)) {
            if (date.length() >= 17) {
                imageInfo.setDay(Utils.getNormalYMDTime(date.substring(0, 10)));
                imageInfo.setMinutes(date.substring(11, 16));
                imageInfo.setDate(date.substring(0, 10));
            } else {
                imageInfo.setDay("");
                imageInfo.setMinutes("");
                imageInfo.setDate("");
            }
        } else {
            imageInfo.setDay("");
            imageInfo.setMinutes("");
            imageInfo.setDate("");
        }
        imageInfo.setLocation(imagePathListBean.getImageUploadLocationProvince() + " " + imagePathListBean.getImageUploadLocationCity());
        return imageInfo;
    }

    private void openFile(DocunmentEntity entity, String title, int position,boolean isError) {
        if (!Utils.isNull(entity.getDataUrl())) {
            String url, name, fileUrl, urls;
            url = entity.getDataUrl();
            urls = url.split("\\?")[0];
            fileUrl = urls.substring(urls.lastIndexOf("/") + 1, urls.length());
            if (MyApp.downloadFiles.contains(title) || !MyApp.mIsInitTBSSuccess||isError) {
                if (!MyApp.docunmentOpen) {
                    Intent intent = new Intent(context, DocumentPreviewActivity.class);
                    intent.putExtra("fileUrl", fileUrl);
                    intent.putExtra("fileName", title);
                    intent.putExtra("dataCode", entity.getDataCode());
                    if (isTask) {
                        intent.putExtra("type", 1);
                    }
                    context.startActivity(intent);
                }
            } else {
//                    downTask(url, title, entity, position);
                entity.setProgress(1);
                notifyItemChanged(position);
                Intent intent = new Intent(context, DownloadService.class);
                intent.putExtra("fileUrl", fileUrl);
                intent.putExtra("fileName", title);
                intent.putExtra("url", url);
                intent.putExtra("dataCode", entity.getDataCode());
                intent.putExtra("position", position);
                intent.putExtra("tag", tag);
                context.startService(intent);
            }

        }
    }

    private void getVideo(String id, int type) {
        Map<String, String> map = new HashMap<>();
        map.put("videoId", id);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<VideoEntity>>() {
        }.getType(), null, Urls.selectAPPVideoById, SignUtils2.makeSignStr(map), false, new ObserverCallback<VideoEntity>() {
            @Override
            public void onSuccess(VideoEntity data) {
                if (Utils.isNull(data.videoId)) {
                    MyToast.show("视频id为空");
                    return;
                }
                if (type == 2) {
                    Intent intent = new Intent(context, VedioDetailActivity.class);
                    intent.putExtra("video", data);
                    context.startActivity(intent);
                } else {
                    Intent intent = new Intent(context, VideoOnePlayActivity.class);
                    intent.putExtra("watermark", "2");
                    intent.putExtra("video", data);
                    context.startActivity(intent);
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void toClickNum(String newsId) {
        Map<String, String> map = new HashMap<>();
        map.put("id", newsId);
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.setClickNum, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void saveScan(String code, String resourceType) {
        Map<String, String> map = new HashMap<>();
        map.put("resourceId", code);
        map.put("resourceType", resourceType);
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.saveScan, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                JSONObject reObject = null;
                try {
                    reObject = new JSONObject(data);
                    if ("200".equals(reObject.getString("code"))) {
                    } else {
                        MyToast.show(reObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(errorMsg);
            }
        });
    }
}
